package com.xiaoshuidi.cloud.module.member.service.questionnaireinfo;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.OptionInfo;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionCreateVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionnaireInfoUpdateVO;
import com.xiaoshuidi.cloud.module.member.mapper.questionnaireinfo.MemberQuestionMapper;
import com.xiaoshuidi.cloud.module.member.pojo.questionnaireinfo.MemberQuestion;
import com.xiaoshuidi.cloud.module.member.repository.MemberOptionRepository;
import com.xiaoshuidi.cloud.module.member.repository.MemberQuestionRepository;
import com.xiaoshuidi.cloud.module.member.repository.MemberQuestionnaireInfoRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberQuestionServiceImpl extends ServiceImpl<MemberQuestionMapper, MemberQuestion> implements MemberQuestionService {

    private final MemberQuestionRepository memberQuestionRepository;

    private final MemberOptionRepository memberOptionRepository;

    private final MemberQuestionnaireInfoRepository memberQuestionnaireInfoRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchCreate(Long questionnaireId, List<QuestionCreateVO> createReqVOs) {

        //提前声明一个容器收集对应题目的选项信息
        List<OptionInfo> list = new ArrayList<>();
        //组装题目对象列表收集选项信息
        List<MemberQuestion> questions = createReqVOs.stream().map(q -> {
            OptionInfo optionInfo = new OptionInfo();
            MemberQuestion memberQuestion = new MemberQuestion();
            BeanUtils.copyProperties(q, memberQuestion);
            long questionId = IdUtil.getSnowflakeNextId();
            optionInfo.setQuestionId(questionId);
            memberQuestion.setId(questionId);
            memberQuestion.setQuestionnaireId(questionnaireId);
            optionInfo.setQuestionnaireId(questionnaireId);
            optionInfo.setOptionItems(q.getOptionItems());
            list.add(optionInfo);
            return memberQuestion;
        }).collect(Collectors.toList());
        //删除以前的题目
        memberQuestionRepository.removeBatchByQuestionnaireId(questionnaireId);
        //批量插入题目表
        memberQuestionRepository.saveBatch(questions);

        //删除以前的选项
        memberOptionRepository.removeBatchByQuestionnaireId(questionnaireId);
        //批量插入选项信息
        memberOptionRepository.batchCreate(list);
        return true;
    }

}
